package coolq.yaozhenyong.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.BeanUtils;

import com.forte.qqrobot.anno.Filter;
import com.forte.qqrobot.anno.Listen;
import com.forte.qqrobot.anno.depend.Beans;
import com.forte.qqrobot.beans.messages.msgget.GroupMsg;
import com.forte.qqrobot.beans.messages.result.GroupMemberInfo;
import com.forte.qqrobot.beans.messages.types.MsgGetTypes;
import com.forte.qqrobot.sender.MsgSender;
import com.forte.qqrobot.utils.CQCodeUtil;

import coolq.yaozhenyong.Impl.ApiCocportImpl;
import coolq.yaozhenyong.bean.ApiCocport;
import coolq.yaozhenyong.bean.Apiport;
import coolq.yaozhenyong.bean.Claninform;
import coolq.yaozhenyong.bean.ClansClan;
import coolq.yaozhenyong.bean.CocGroupUser;
import coolq.yaozhenyong.bean.CocQq;
import coolq.yaozhenyong.bean.CocQqRemove;
import coolq.yaozhenyong.bean.GradeAdmin;
import coolq.yaozhenyong.bean.GradeAdministrator;
import coolq.yaozhenyong.bean.SysUser;
import coolq.yaozhenyong.cocApi.custom.ClansPlayersTagCustom;
import coolq.yaozhenyong.cocApi.entity.ClansPlayersTag.ClansPlayersTag;
import coolq.yaozhenyong.cocApi.entity.ClansPlayersTag.Heroes;
import coolq.yaozhenyong.custom.CocCustom;
import coolq.yaozhenyong.custom.QqCqcustom;
import coolq.yaozhenyong.custom.SpringContextUtil;
import coolq.yaozhenyong.custom.TimeUtils;
import coolq.yaozhenyong.custom.entity.ems.Ems;
import coolq.yaozhenyong.custom.entity.ems.Remark;
import coolq.yaozhenyong.service.ApiportService;
import coolq.yaozhenyong.service.ClaninformService;
import coolq.yaozhenyong.service.ClansClanService;
import coolq.yaozhenyong.service.CocGroupUserService;
import coolq.yaozhenyong.service.CocQqRemoveService;
import coolq.yaozhenyong.service.CocQqService;
import coolq.yaozhenyong.service.GradeAdminService;
import coolq.yaozhenyong.service.GradeAdministratorService;
import coolq.yaozhenyong.service.GroupListService;
import coolq.yaozhenyong.service.SysUserService;

/*@Beans*/
public class QQGroupAtController {
	public GradeAdminService gService = SpringContextUtil.getBean(GradeAdminService.class);
	public GradeAdministratorService gradeservice = SpringContextUtil.getBean(GradeAdministratorService.class);
	public CocGroupUserService CocService = SpringContextUtil.getBean(CocGroupUserService.class);
	public GroupListService grouplistservice = SpringContextUtil.getBean(GroupListService.class);
	/*@Listen(MsgGetTypes.groupMsg)
	@Filter(at=true)	*/
	public void home(GroupMsg msg,CQCodeUtil cqCodeUtil,MsgSender msgsender) throws InterruptedException {
		/*if(msg.getQQ().equals("2854196310")||msg.getQQ().equals("2854196312")||msg.getQQ().equals("2854196306")||"qq点歌".indexOf(msg.getMsg())!=-1||"网易点歌".indexOf(msg.getMsg())!=-1) {
			return ;
		}
		grouplistservice.update().eq("groupcode", msg.getGroup()).set("endtime", TimeUtils.getStringDate()).update();
		*//** 判断这个群机器人是否为开启状态 **//*
		GradeAdmin gradeadmin = gService.query().eq("gradenumber", msg.getGroup()).eq("codes", "robot").eq("isgoto", "1").one();
		if(gradeadmin!=null) {
			// 1.首先取出字段	
			String m = cqCodeUtil.removeCQCodeFromMsg(msg.getMsg());
			m = m.replaceAll(" ", "").replaceAll("	", "").replaceAll(",", "").replaceAll("\r", "").replaceAll("\n", "").replaceAll("\t", "").replaceAll("＃", "#");
			if("部落阵型".equals(m)||"COC阵型".equals(m)||"coc阵型".equals(m)||"部落鱼情".equals(m)||"coc鱼情".equals(m)||"查询鱼情".equals(m)||"查询部落鱼情".equals(m)||"查询coc鱼情".equals(m)||"玩家状态".equals(m)||"全球玩家状态".equals(m)) {
				if("部落阵型".equals(m)||"COC阵型".equals(m)||"coc阵型".equals(m)) {
					return ;
				}
				ApiportService service = SpringContextUtil.getBean(ApiportService.class);
				Apiport ones = service.query().eq("qqnumber", msg.getGroup()).eq("type","coc").eq("isgoto", "1").one();
				if(ones!=null) {
					yuqing(cqCodeUtil,msgsender,msg);
					return ;
				}
			}
			//处理快递
			if(m.length()>0) {
				if(m.length()>4&&(m.indexOf("绑定")!=-1||m.indexOf("查询")!=-1||m.indexOf("部落")!=-1||m.indexOf("村庄")!=-1)) {
					*//** 绑定部落 **//*
					try {
						Boolean cocbangding = cocbangding(msg,cqCodeUtil,msgsender,m);
						if(cocbangding) {
							return ;
						}
					} catch (Exception e) {
						System.err.println("绑定部落报错了!时间："+TimeUtils.getStringDate());
						return ;
					}
					
					*//** 查询村庄 **//*
					try {
						Boolean coc = coc(msg,cqCodeUtil,msgsender,m);
						if(coc) {
							return ;
						}
					} catch (Exception e) {
						System.err.println("查询部落报错了!时间："+TimeUtils.getStringDate());
						return ;
					}
					*//** 查询快递 **//*
					try {
						Boolean ems = ems(msg,cqCodeUtil,msgsender,m);
						if(ems) {
							return ;
						}
					} catch (Exception e) {
						System.err.println("查询快递报错了!时间："+TimeUtils.getStringDate());
						return ;
					}
					
					*//** 部落报名 **//*
					try {
						boolean cocqq = cocqq(msg,cqCodeUtil,msgsender, m);
						if(cocqq) {
							return ;
						}
					} catch (Exception e) {
						e.printStackTrace();
						System.err.println("部落报名出错了!时间："+TimeUtils.getStringDate());
						return ;
					}
				}
				try {
					Boolean groupUser = cocGroupUser(msg,cqCodeUtil,msgsender,m);
					if(groupUser) {
						return ;
					}
				} catch (Exception e) {
					System.err.println("COC绑定查询部落报错了!时间："+TimeUtils.getStringDate());
					return ;
				}
				if(msg.getQQ().equals("936642284")) {
					//群广播功能指令
					Boolean broadcast = broadcast(msg,cqCodeUtil,msgsender);
					if(broadcast) {
						return ;
					}
				}
				
			}else {
			}
			
		}*/
	
	}
	
	private void yuqing(CQCodeUtil cqCodeUtil, MsgSender msgsender, GroupMsg msg) {
		String[] c = MyqqRobot.clashofclansforecaster;
		long datadifference = TimeUtils.datadifference(c[1]);
		if(datadifference<120&&"1".equals(c[2])) {
			msgsender.SENDER.sendGroupMsg(msg.getGroup(), c[0]);
		}else {
			String goyuqing = CocCustom.goyuqing();
			if(goyuqing==null) {
				MyqqRobot.clashofclansforecaster[2] = "0";
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), c[0] + "\n◎━"+datadifference/60+"分钟前获取━◎");
			}else {
				MyqqRobot.clashofclansforecaster[0] = goyuqing;
				MyqqRobot.clashofclansforecaster[1] = TimeUtils.getStringDate();
				MyqqRobot.clashofclansforecaster[2] = "1";
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), goyuqing);
			}
		}
	}

	/**
	 * coc 部落战 联赛报名
	 * @param msg
	 * @param cqCodeUtil
	 * @param m
	 * @return
	 */
	private boolean cocqq(GroupMsg msg, CQCodeUtil cqCodeUtil,MsgSender msgsender, String m) {
		String[] split = m.split("#");
		if(split.length==3&&"退出".equals(split[2])) {
			ClaninformService clanservice = SpringContextUtil.getBean(ClaninformService.class);
			Claninform clan = clanservice.query().eq("qunnumber", msg.getGroup()).eq("kenning", split[0]).eq("isgoto", "1").one();
			
			ClansClanService clansclanservice = SpringContextUtil.getBean(ClansClanService.class);
			ClansClan clansclan = clansclanservice.query().eq("id", clan.getClansclanId()).one();
			
			CocQqService cocqqservice = SpringContextUtil.getBean(CocQqService.class);
			String upperCase = split[1].toUpperCase();
			try {
				CocQq cocqq = cocqqservice.query().eq("uuid", clansclan.getUuid()).eq("tag", "#"+upperCase).eq("qunnumber", msg.getGroup()).one();
				if(cocqq!=null) {
					CocQqRemoveService cocremoveservice = SpringContextUtil.getBean(CocQqRemoveService.class);
					CocQqRemove remove = new CocQqRemove();
					//判断是否是同一个人绑定的！
					if(cocqq.getQqnumber().equals(msg.getQQ())) {
						
						BeanUtils.copyProperties(cocqq, remove,"id");
						
						cocqqservice.removeById(cocqq);
						remove.setRemoveqqnumber(msg.getQQ());
						cocremoveservice.save(remove);
						msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ()) +" 您的村庄【"+cocqq.getTagname()+"】已成功退出本次【"+clansclan.getName()+"】的"+clan.getType()+"的报名。");
					}else{
						GradeAdministrator one = gradeservice.query().eq("qunnumber", msg.getGroup()).eq("qqnumber", msg.getQQ()).eq("cocgoto", "1").one();
						if(one!=null) {
							BeanUtils.copyProperties(cocqq, remove,"id");
							cocqqservice.removeById(cocqq);
							remove.setRemoveqqnumber(msg.getQQ());
							cocremoveservice.save(remove);
							msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ()) +" 你已取消"+cqCodeUtil.getCQCode_At(cocqq.getQqnumber())+" 【"+cocqq.getTagname()+"】在【"+clansclan.getName()+"】部落"+clan.getType()+"的报名。");
							return true;
						}
						msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ()) +" 除了本人和代管以外，其他人不可以取消别人的报名！");
						return true;
					}
					return true;
				}else {
					msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ()) +" 未查到#"+upperCase+"的报名情况！");
					return true;
				}
			} catch (Exception e) {
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ()) +" 取消失败，请找本群的机器人管理员去后台删除");
			}
			
			
		}else if(split.length==2&&split[1].equals("报名情况")) {
			ClaninformService clanservice = SpringContextUtil.getBean(ClaninformService.class);
			Claninform clan = clanservice.query().eq("qunnumber", msg.getGroup()).eq("kenning", split[0]).eq("isgoto", "1").one();
			
			ClansClanService clansclanservice = SpringContextUtil.getBean(ClansClanService.class);
			ClansClan clansclan = clansclanservice.query().eq("id", clan.getClansclanId()).one();
			
			CocQqService cocqqservice = SpringContextUtil.getBean(CocQqService.class);
			List<CocQq> list = cocqqservice.query().eq("uuid", clansclan.getUuid()).eq("qunnumber", msg.getGroup()).orderBy(true, false, "CAST(versus_battle_win_count as SIGNED)").list();
			
			msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+""
					+ "\n● "+clansclan.getName()
					+ "\n● 报名人数："+list.size()+"\n● 报名名单已私聊 \n● 报名情况（网站）：http://yzycoc.com/qq/cocApi/apply?tag="+clansclan.getUuid());
			String reply ="报名名单（简略）";
			for (CocQq cocQq : list) {
				String re = "";
				if(cocQq.getTownHallWeaponLevel()!=null) {
					re ="(" +cocQq.getTownHallWeaponLevel()+"[CQ:emoji,id=11088])";
				}
				reply += "\n\n● 名称:"+cocQq.getTagname()
						+ "\n● 标签:"+cocQq.getTag()
						+ "\n● 大本:"+cocQq.getTownHallLevel()+re
						+ "\n● 蛮王"+cocQq.getBarbarianKing()+" 女皇"+cocQq.getArcherQueen()+" 咏王"+cocQq.getGrandWarden()
						+ "\n● 匹配值"+cocQq.getVersusBattleWinCount();
			}
			msgsender.SENDER.sendPrivateMsg(msg.getQQ(), reply+"\n\n● 报名情况（网站）：http://yzycoc.com/qqrobot/cocApi/apply?tag="+clansclan.getUuid());
			return true;
		}else if(split.length>1) {
			ClaninformService clanservice = SpringContextUtil.getBean(ClaninformService.class);
			Claninform clan = clanservice.query().eq("qunnumber", msg.getGroup()).eq("kenning", split[0]).eq("isgoto", "1").one();
			//是否存在这个联赛报名
			try {
				if(clan!=null) {//存在
					//查询玩家是否存在
					msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+" 正在连接网络查询【#"+ split[1]+"】的村庄信息！请等待...");
					ClansPlayersTag findAll = ClansPlayersTagCustom.findAll(split[1]);
					if(findAll!=null&&findAll.getDataisnull()) {
						ClansClanService clansclanservice = SpringContextUtil.getBean(ClansClanService.class);
						ClansClan clansclan = clansclanservice.query().eq("id", clan.getClansclanId()).one();
						CocQqService cocqqservice = SpringContextUtil.getBean(CocQqService.class);
						CocQq cocqq = cocqqservice.query().eq("uuid", clansclan.getUuid()).eq("tag", findAll.getTag()).eq("qunnumber", msg.getGroup()).one();
						if(cocqq!=null) {//存在这个用户，更新数据
							//查询如果此用户已报名，防止用户二次报名
							List<Heroes> heroes = findAll.getHeroes();
							if(heroes!=null) {
								for (Heroes h : heroes) {
									if("Barbarian King".equals(h.getName())) {
										cocqq.setBarbarianKing(h.getLevel());
										continue;
									}
									if("Archer Queen".equals(h.getName())) {
										cocqq.setArcherQueen(h.getLevel());
										continue;
									}
									if("Grand Warden".equals(h.getName())) {
										cocqq.setGrandWarden(h.getLevel());
										continue;
									}
								}
							}
							cocqq.setTownHallLevel(findAll.getTownHallLevel());
							if(findAll.getTownHallWeaponLevel()!=null) {
								cocqq.setTownHallWeaponLevel(findAll.getTownHallWeaponLevel());
							}
							String clantag = findAll.getClan()==null?"":findAll.getClan().getTag();
							if(clantag.equals(clansclan.getTag())) {
								cocqq.setIsgoto(true);
							}else {
								cocqq.setIsgoto(false);
							}
							cocqq.setVersusBattleWinCount(findAll.getVersusBattleWinCount());
							if(split.length==3) {
								String remark = cocqq.getRemark()==null?"":cocqq.getRemark();
								String sp =split[2]==null?"":split[2];
								if(!sp.equals(remark)) {
									cocqqservice.updateById(cocqq);
									cocqq.setRemark(split[2]);
									msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ()) + " 已更新备注!");
									return true;
								}
							}
							cocqqservice.updateById(cocqq);
							String reply = cqCodeUtil.getCQCode_At(msg.getQQ())+" "
									+ "玩家【"+findAll.getName()+"】"+findAll.getTag()+"已经参与了本次"+clan.getType()+"报名，请不要重复报名！\n"
									+ "报名人"+cocqq.getQqnumber()+"  报名时间\n"+cocqq.getCreateDate()+"\n如需取消本次报名：\n@我 "+clan.getKenning()+"#标签#退出";
							msgsender.SENDER.sendGroupMsg(msg.getGroup(), reply);
							return true;
						}else {//不存在这个用户，完全重新报名
							cocqq = new CocQq();
							//保存
							try {
								GroupMemberInfo groupMemberInfo = msgsender.GETTER.getGroupMemberInfo(msg.getGroup(),msg.getQQ());
								cocqq.setQqimageurl(groupMemberInfo.getHeadImgUrl());
								String card = groupMemberInfo.getCard();
								if(card==null||card==""||card.length()<1) {
									card = groupMemberInfo.getName();
								}
								cocqq.setName(card);
							} catch (Exception e) {
							}
							cocqq.setUuid(clansclan.getUuid());
							cocqq.setQunnumber(msg.getGroup());
							cocqq.setQqnumber(msg.getQQ());
							cocqq.setTag(findAll.getTag());
							cocqq.setTagname(findAll.getName());
							cocqq.setTownHallLevel(findAll.getTownHallLevel());
							if(findAll.getTownHallWeaponLevel()!=null) {
								cocqq.setTownHallWeaponLevel(findAll.getTownHallWeaponLevel());
							}
							
							cocqq.setExpLevel(findAll.getExpLevel());
							cocqq.setTrophies(findAll.getTrophies());
							cocqq.setWarStars(findAll.getWarStars());
							cocqq.setAttackWins(findAll.getAttackWins());
							cocqq.setDefenseWins(findAll.getDefenseWins());
							cocqq.setVersusBattleWinCount(findAll.getVersusBattleWinCount());
							String league =findAll.getLeague()==null?"":findAll.getLeague().getIconUrls()==null?"":findAll.getLeague().getIconUrls().getSmall();
							cocqq.setLeague(league);
							cocqq.setCreateDate(TimeUtils.getStringDate());
							List<Heroes> heroes = findAll.getHeroes();
							if(heroes!=null) {
								for (Heroes h : heroes) {
									if("Barbarian King".equals(h.getName())) {
										cocqq.setBarbarianKing(h.getLevel());
										continue;
									}
									if("Archer Queen".equals(h.getName())) {
										cocqq.setArcherQueen(h.getLevel());
										continue;
									}
									if("Grand Warden".equals(h.getName())) {
										cocqq.setGrandWarden(h.getLevel());
										continue;
									}
								}
							}
							String clantag = findAll.getClan()==null?"":findAll.getClan().getTag();
							
							String reply = " 【"+findAll.getName()+"】"+findAll.getTag()+"您已成功报名【"+clansclan.getName()+"】部落的部落战！";
							if(clantag.equals(clansclan.getTag())) {
								cocqq.setIsgoto(true);
							}else {
								cocqq.setIsgoto(false);
								reply =reply + "\n您现在还不在部落内，请尽早回归部落方便开战！";
							}
							cocqq.setRemoves(true);
							if(split.length==3) {
								cocqq.setRemark(split[2]);
							}
							//保存前在确定一下这个用户是否报名过
							CocQq cocqq2 = cocqqservice.query().eq("uuid", clansclan.getUuid()).eq("tag", findAll.getTag()).eq("qunnumber", msg.getGroup()).one();
							if(cocqq2==null) {
								cocqqservice.save(cocqq);
								msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+reply);
							}else {
								String replys = cqCodeUtil.getCQCode_At(msg.getQQ())+" "
										+ "玩家【"+findAll.getName()+"】"+findAll.getTag()+"已经参与了本次"+clan.getType()+"报名，请不要重复报名！\n"
										+ "报名人"+cocqq.getQqnumber()+"  报名时间\n"+cocqq.getCreateDate()+"\n如需取消本次报名：\n@我 "+clan.getKenning()+"#标签#退出";
								msgsender.SENDER.sendGroupMsg(msg.getGroup(), replys);
							}
						}
					}else {
						//无法查找到玩家信息
						String replyto = findAll==null?"未知！":findAll.getError();
						replyto = "报名失败！因为需要查询游戏信息，现无法获取，所以无法报名，请稍后重试！\n出现的问题：\n"+replyto;
						msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+replyto);
					}
					return true;
				}
			} catch (Exception e) {
				String  replyto = "报名失败！因为需要查询游戏信息，现无法获取，所以无法报名，请稍后重试！\n出现的问题：\n请截屏反馈给作者！";
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+replyto);
			}
			
		}
		return false;
	}
	/****
	 * 查找绑定对应的
	 * @param msg
	 * @param cqCodeUtil
	 * @param msgsender
	 * @param m
	 * @return
	 */
	private Boolean cocGroupUser(GroupMsg msg, CQCodeUtil cqCodeUtil, MsgSender msgsender, String m) {
		CocGroupUser one = CocService.query().eq("groupnumber", msg.getGroup()).eq("msg", m).one();
		if(one!=null) {
			String groupmsg = cqCodeUtil.getCQCode_At(msg.getQQ()) +" ";
			ApiportService service = SpringContextUtil.getBean(ApiportService.class);
			Apiport ones = service.query().eq("qqnumber", msg.getGroup()).eq("type","coc").eq("isgoto", "1").one();
			if(ones!=null) {
				ApiCocportImpl apicoc = SpringContextUtil.getBean(ApiCocportImpl.class);
				ApiCocport Cocport = apicoc.query().eq("uuid", ones.getAppkey()).one();
				if(Cocport!=null&&Cocport.getResidue()>0) {
					msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+" 正在连接网络查询"+one.getType()+"【#"+ one.getCoctag()+"】的相关信息！请耐心等待。。。");
					CocCustom.goCocUrl(one.getType(), one.getCoctag(), msg, cqCodeUtil, msgsender);
					ones.setSum(ones.getSum()+1);
					Cocport.setResidue(Cocport.getResidue()-1);
					apicoc.updateById(Cocport);
					service.updateById(ones);
					return true;
				}else {
					groupmsg +="本群今日使用次数已达上限，心疼一下服务器吧；\n他太累了，让他休息一下！";
				}
			}else {
				groupmsg +="本群还未开通此功能！";
			}
			msgsender.SENDER.sendGroupMsg(msg.getGroup(),groupmsg);
			return true;
		}
		return false;
	}
	/****
	 * 绑定
	 * @param msg
	 * @param cqCodeUtil
	 * @param msgsender
	 * @param m
	 * @return
	 */
	private Boolean cocbangding(GroupMsg msg, CQCodeUtil cqCodeUtil, MsgSender msgsender, String m) {
		
		String substring = m.substring(0, 4);
		if(substring.equals("绑定村庄")||substring.equals("绑定部落")) {
			ApiportService service = SpringContextUtil.getBean(ApiportService.class);
			Apiport ones = service.query().eq("qqnumber", msg.getGroup()).eq("type","coc").eq("isgoto", "1").one();
			if(ones==null) {
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+" 此群还未启用此功能哦！");
				return true;
			}
			GradeAdministrator one = gradeservice.query().eq("qunnumber", msg.getGroup()).eq("qqnumber", msg.getQQ()).eq("cocgoto", "1").one();
			if(one!=null) {
				String groupmsg = cqCodeUtil.getCQCode_At(msg.getQQ())+" ";
				String[] split = m.split("#");
				if(split.length==3) {
					if(split[0].length()>0&&split[1].length()>0&&split[2].length()>1) {
						CocGroupUser one2 = CocService.query().eq("groupnumber", msg.getGroup()).eq("msg", split[2]).one();
						if(one2!=null) {
							groupmsg += "【"+split[2]+"】此代称在本群已被绑定，请换一个吧！";
						}else {
							msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+" 正在联网查询【#"+split[1]+"】"+m.substring(2,4)+"是否存在！请耐心等待。。。");
							Boolean goCocBd = QqCqcustom.goCocBd(split);
							if(goCocBd) {
								CocGroupUser cocgroupuser = new CocGroupUser(TimeUtils.getStringDate(),msg.getGroup(),msg.getQQ(),split[2],m.substring(2,4),split[1]);
								CocService.save(cocgroupuser);
								groupmsg +="绑定成功，以后【@我 "+split[2]+"】即可获取"+split[1]+"的"+m.substring(2,4)+"信息";
							}else {
								groupmsg += "【#"+split[1]+"】此标签无法查到对于"+m.substring(2,4)+"的信息,请核对后再绑定！\n\n推荐直接进游戏复制标签哦！";
							}
						}
					}else if(split[1].length()==0){
						groupmsg += "标签格式错误！";
					}else if(split[2].length()<2) {
						groupmsg +="代称的长度必须大于2位！";
					}else {
						groupmsg += "格式错误哦，正确的格式为:"+substring+"#标签#代称";
					}
				}else {
					groupmsg += "格式错误哦，正确的格式为:"+substring+"#标签#代称";
				}
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), groupmsg);
			}else {
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+" 在此群你还没有权力绑定自己的coc，请联系相关代管进行绑定！\r\n\r\n"
						+ "你也可以添加我为好友进行个人绑定，私聊我也是可以获得自己coc信息！");
			}
			
			return true;
		}
		return false;
	}
	/***
	 * 图灵机器人智能聊天
	 * @param msg
	 * @param cqCodeUtil
	 * @param msgsender
	 * @param m
	 */
	public static void tuling(GroupMsg msg, CQCodeUtil cqCodeUtil, MsgSender msgsender, String m) {
		ApiportService service = SpringContextUtil.getBean(ApiportService.class);
		Apiport one = service.query().eq("qqnumber", msg.getGroup()).eq("type","tuling").eq("isgoto", "1").one();
		if(one!=null) {
			String goTulingUrl = QqCqcustom.goTulingUrl(one.getAppkey(),m);
			msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+"  "+goTulingUrl);
			one.setSum(one.getSum()+1);
			service.updateById(one);
		}
	}
	/****
	 * 跳转到部落查询
	 * @param msg
	 * @param cqCodeUtil
	 * @param msgsender
	 * @param m
	 * @return
	 */
	private Boolean coc(GroupMsg msg, CQCodeUtil cqCodeUtil, MsgSender msgsender, String m) {
		String[] split = m.split("#");
		if(split.length==2) {
			String substring = split[0];
			substring = substring.replaceAll(" ", "");
			if(substring.equals("我的村庄")||substring.equals("我的部落")||substring.equals("查询部落")||substring.equals("查询村庄")||substring.equals("查询玩家")||substring.equals("查询部落配置")||substring.equals("部落配置")) {
				ApiportService service = SpringContextUtil.getBean(ApiportService.class);
				Apiport one = service.query().eq("qqnumber", msg.getGroup()).eq("type","coc").eq("isgoto", "1").one();
				if(one!=null) {
					ApiCocportImpl apicoc = SpringContextUtil.getBean(ApiCocportImpl.class);
					ApiCocport Cocport = apicoc.query().eq("uuid", one.getAppkey()).one();
					if(Cocport!=null&&Cocport.getResidue()>0) {
						try {
							String blpz =" 请等待";
							if(substring.equals("查询部落配置")||substring.equals("部落配置")) {
								SysUserService sysuserservice = SpringContextUtil.getBean(SysUserService.class);
								SysUser sys = sysuserservice.query().eq("username", msg.getGroup()).one();
								if(sys==null||sys.getAdministratoring()==null||sys.getAdministratoring()==false) {
									msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+" 本群还无法使用此功能！");
									return true;
								}
								blpz =" 查询配置需要的时间比较长，请耐心等待..."; 
							}
							msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+blpz);
							CocCustom.goCocUrl(substring,split[1],msg,cqCodeUtil,msgsender);
							one.setSum(one.getSum()+1);
							Cocport.setResidue(Cocport.getResidue()-1);
							apicoc.updateById(Cocport);
							service.updateById(one);
						} catch (Exception e) {
							e.printStackTrace();
							String goCocUrl = " 未查到你的#"+split[1]+"信息哦！";
							msgsender.SENDER.sendPrivateMsg("936642284",split[1]+"的标签好像出问题了！记住此标签，出现bug了！" );
							msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+" "+ goCocUrl);
						}
						return true;
					}else {
						msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+" 本群今日使用次数已达上限！\n心疼一下服务器吧，他太累了，让他休息一下" );
						return true;
					}
				}else {
					msgsender.SENDER.sendGroupMsg(msg.getGroup(),cqCodeUtil.getCQCode_At(msg.getQQ())+" 本群还未启用此功能！");
				}
				return true;
			}
			
		}
		return false;
	}
	/***
	 *	处理发送快递信息
	 * @param msg
	 * @param cqCodeUtil
	 * @param msgsender
	 * @param m
	 * @return false未处理 true 已处理
	 */
	private Boolean ems(GroupMsg msg, CQCodeUtil cqCodeUtil, MsgSender msgsender, String m) {
		String substring = m.substring(0, 4);
		if(substring.equals("查询快递")) {
			ApiportService service = SpringContextUtil.getBean(ApiportService.class);
			Apiport one = service.query().eq("qqnumber", msg.getGroup()).eq("type","ems").eq("isgoto", "1").one();
			if(one!=null) {
				Pattern pattern = Pattern.compile("[A-Za-z0-9]");
				Matcher matcher = pattern.matcher(m);
				 if (matcher.find()) {
					 int indexOf = m.indexOf(matcher.group());
					 if(indexOf<=4) {
						 msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+"你查询快递的格式错误哦！");
						 return true;
					 }else {
						 //快递名称
						 String kuaidi = m.substring(4,indexOf);
						 String substring2 = m.substring(indexOf,m.length());
						 String ems = QqCqcustom.ems(kuaidi);
						 if(ems==null) {
							 msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+"你查询"+kuaidi+"我不晓得哪个公司哦");
							 return true;
						 }else{
							 /** 成功使用 **/
							 one.setSum(one.getSum()+1);
							 service.updateById(one);
							 String[] emsNumber = getEmsNumber(substring2);
							 Ems emsUrl = new Ems();
							 if(emsNumber.length==1) {
								 emsUrl = QqCqcustom.toEmsUrl(one.getAppkey(),ems,emsNumber[0],"");
							 }else if(emsNumber.length==2){
								 emsUrl = QqCqcustom.toEmsUrl(one.getAppkey(),ems,emsNumber[0],emsNumber[1]);
							 }else {
								 msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+substring2+"这个我无法给你查询哦！");
								 return true;
							 }
							 String privatemsg ="";
							 if(emsUrl!=null) {
								 /*** 处理最后返回的结果集 ***/
								 String emsmsg = cqCodeUtil.getCQCode_At(msg.getQQ())+" ";
								 if(emsUrl.getResultcode().equals("200")&&emsUrl.getError_code().equals("0")) {
									 //群发
									 List<Remark> list = new ArrayList<Remark>();
									 if(emsUrl.getResult()!=null&&emsUrl.getResult().getList().size()>0) {
										 privatemsg = "您快递的详细信息：\n快递号："+emsUrl.getResult().getNo()+"\n";
										 list = emsUrl.getResult().getList();
									 }
									 if(list.size()>0) {
										 emsmsg += "您快递最新消息：\n\n"+list.get(list.size()-1).getDatetime()+"\n"+list.get(list.size()-1).getRemark()+"\n\n物流详细信息已私聊，如未收到消息，请添加我为好友哦！";
										 for (Remark remark : list) {
											 privatemsg += remark.getDatetime()+"\n"+remark.getRemark()+"\n\n";
										}
										 msgsender.SENDER.sendPrivateMsg(msg.getQQ(), privatemsg+"如果不想接收消息，你可以屏蔽我哦！");
									 }else {
										 if(emsUrl.getResult()!=null) {
											 emsmsg +=QqCqcustom.status_detail(emsUrl.getResult().getStatus_detail());
										 }else {
											 emsmsg +="无法查询此次快递！";
											 msgsender.SENDER.sendPrivateMsg("936642284", msg.getGroup()+"群的群员"+msg.getQQ()+"查询快递"+msg.getMsg()+"出现错误!"+"\n错误原因是"+emsUrl.getReason());
										 }
									 }
								 }else {
									 String rtnUrl = QqCqcustom.returnUrl(emsUrl.getResultcode(),emsUrl.getError_code());
									 emsmsg += rtnUrl;
								 }
								 
								 msgsender.SENDER.sendGroupMsg(msg.getGroup(), emsmsg);
								 return true;
							 }else {
								 msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+"恕在下能力浅薄，未能根据你的需要查找出对应的快递信息！");
								 return true;
							 }
						 }
						
					 }
				 }
			}
			return false;
		}
		return false;
	}
	/****
	 * 
	 * @param string 除开条件后的参数
	 * return 最后字段的筛选
	 * @return 
	 */
	private String[] getEmsNumber(String string) {
		if(string.indexOf("收")!=-1) {
			String[] a = string.split("收");
			a[1] = "&senderPhone="+a[1];
			return a;
		}else if(string.indexOf("寄")!=-1) {
			String[] a = string.split("寄");
			a[1] = "&receiverPhone="+a[1];
			return a;
		}else {
			String[] a = {string};
			return a;
		}
	}
	/***
	 * 
	 * @param msg
	 * @param cqCodeUtil
	 * @param msgsender
	 * @return
	 */
	private Boolean broadcast(GroupMsg msg, CQCodeUtil cqCodeUtil, MsgSender msgsender) {
		String[] split = msg.getMsg().split(" ");
		if(split.length == 4&&"群广播".equals(split[1])) {
			try {
				GroupListService group = SpringContextUtil.getBean(GroupListService.class);
				if(split[3].equals("开启")||split[3].equals("关闭")) {
					boolean update = group.update().eq("groupcode", split[2]).set("borad", split[3].equals("开启")?2:1).update();
					msgsender.SENDER.sendGroupMsg(msg.getGroup(), update+"群"+split[2]+"的群广播功能 "+split[3]);
				}else {
					msgsender.SENDER.sendGroupMsg(msg.getGroup(), "格式为@我 群广播 群号 开启/关闭");
				}
				return true;
			} catch (Exception e) {
				msgsender.SENDER.sendGroupMsg(msg.getGroup(), "报错，格式为@我 群广播 群号 开启/关闭");
				return true;
			}
		}
		return false;
	}
}
